import {Input, List} from "antd";
import {useState, useTransition} from "react";


interface ListItem {
  id: number;
  name: string;
  address: string;
}

const UseTransitionPage = () => {

  const [val, setVal] = useState('')
  const [list, setList] = useState<ListItem[]>([])

  const [isPending, startTransition] = useTransition()
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value
    setVal(value)

    // 模拟获取1000条数据
    fetch(
      '/api/list?keyWord=' + value
    )
      .then((res) => res.json())
      .then(res => {
        console.log('res:', res);
        // 1. 不使用过度函数，直接默认走
        // setList(res.list || [])

        // 2.使用过度函数：
        startTransition(()=>{
          setList(res.list || [])
        })
      })
  }

  return (
    <>
      <div>UseTransitionPage</div>
      <h2>输入很快的时候，页面会卡顿（1000条数据）</h2>
      输入的值：{val} <br/>
      <Input value={val} onChange={handleChange}/>

      <div>
        {isPending && (<div>正在加载中...</div>)}
        <List dataSource={list} renderItem={
          (item) => <List.Item>
            <List.Item.Meta title={item.name} description={item.address}/>
          </List.Item>
        }></List>
      </div>
    </>
  )
}


export default UseTransitionPage;
